﻿using UnityEngine;
using System.Collections;
using System;



//顶级父类，用于消息 和 资源管理(OnExit)
/*
 * 
 *
 */
public class ZT_Object : IDisposable
{


    // every frame will be call
    public virtual void Update()
    {

    }

    //every logic frame will be call(Frame Sync to All clients)
    public virtual void UpdateMS()
    {

    }

    //use this to init you class
    public virtual bool Init()
    {
        return true;
    }

    public virtual void OnEvent(string type, object userData)
    {

    }
    public virtual void OnEvent(int type, object userData)
    {

    }

    // you can override  this interface to release your Res ,Rem. must call base.OnExit when you override
    public virtual void OnExit()
    {

    }


    // you can use this interface to  notify class to release//OnExit will be call
    // use this or Release()
    public void Dispose()
    {
        this.OnExit();
    }
    // use this or Dispose()


    /// <summary>
    /// 立刻释放
    /// </summary>
    public void Release()
    {
        this.Dispose();
    }
    /// <summary>
    /// 下一帧才释放
    /// </summary>
    public void LazyDispose()
    {
        AutoReleasePool.ins.AddObject(this);
    }

    public bool IsValid() { return !isInAutoReleasePool; }
    public bool IsInValid() { return isInAutoReleasePool; }


    public bool isInAutoReleasePool = false;
};



public class AutoReleasePool
{
    public static AutoReleasePool ins
    {
        get
        {
            return AutoReleasePool.GetInstance();
        }
    }

    private static AutoReleasePool _ins = null;

    public static AutoReleasePool GetInstance()
    {
        if (_ins == null)
        {
            _ins = new AutoReleasePool();
        }
        return _ins;
    }


    public static void DestroyInstance()
    {
        _ins.Clear();
        _ins = null;
    }


    public void AddObject(ZT_Object obj)
    {
        if(list.Contains(obj))
        {
            Debug.LogWarning("AutoReleasePool:Obj has been in pool");
            return;
        }
        list.Add(obj);
        obj.isInAutoReleasePool = true;
    }

    public void Clear()
    {
        foreach (ZT_Object obj in list)
        {
            obj.Dispose();
        }
        list.Clear();
    }



    ArrayList list = new ArrayList();


}